const db=require("../db/index")

exports.sourceList=(req,res)=>{
   
   
    let page=req.params.page
    let limit=(page-1)*8
    let dataset=[]
    let sql=""
    let csql=""
    let arr=[]
    if(req.fields[0]){   
        for (const key in req.fields) {
            arr.push(req.fields[key]);
        }
        dataset=[arr,limit] 
        sql='select id,sourcename,sourcedescription,sourceimage,url,author from source where id in ( select sid from `s-t` where tid in (select id from tag where tagname in (?))) limit ?,8;'
        csql='select count(*) from source where id in (select sid from `s-t` where tid in (select id from tag where tagname in (?)));'
    }else{
        dataset= [limit]
        sql='select s.id,s.sourcename,s.sourcedescription,s.sourceimage,s.url,s.author,st.id as lid from source s Left JOIN store st on (st.sid=s.id and st.uid=1) limit ?,8'
        csql='select count(*) from source'
    }
    
   let tsql='select tag.tagname,`s-t`.sid FROM tag LEFT JOIN `s-t` ON `s-t`.tid=tag.id'
   
    let children={
        id:0,sourcename:"",sourceimage:"",url:"",author:"",tag:[]
    }
    let data= new Array();
    //查询资源列表
    db.query(sql,dataset,(err,results)=>{
        if(err)return res.R(err)
        //查询标签
        db.query(tsql,(err,results2)=>{
            if(err)return res.R(err)
            //查询资源总数
            db.query(csql,[arr],(err,results3)=>{
                if(err)return res.R(err)
                results.forEach(item1=>{
                    let tag=[]
                    results2.forEach(item2=>{
                        if(item1.id===item2.sid){
                            tag.push(item2.tagname)
                        }
                    })
                    let a = JSON.stringify(item1);
                    children=JSON.parse(a)
                    data.push({children,tag})
                   
                })
                return res.send({
                    status:200,
                    data,
                    total:results3[0]['count(*)'],
                    message:"获取成功！"
                })

            })
          
        })
    })
}
exports.sourceInfo=(req,res)=>{
    sql="select * from source where id=?"
    id=req.params.id
    if(!id)return res.R("资源id为空！")
    db.query(sql,id,(err,results)=>{
        if(err)return res.R(err)
        if(results.length!==1)return res.R("资源不存在！")
        return res.send({
            message:"获取资源信息成功！",
            status:200,
            data:results[0]
        })
    })
}